<template>
  <view class="sure-exchange">
    <customHeader
      class="custom-title"
      title="确认兑换"
      :isCustomBack="true"
      @back="handleBackPrevPage"
    />
    <view class="sure-exchange-title">
      <image :lazy-load="true" class="head-img" :src="info.goods_cover" />
      <view class="head-title">
        <view>{{ info.goods_name }}</view>
        <view>
          <text>{{ info.use_petal_num }}</text
          ><text>花朵</text>
        </view>
      </view>
    </view>
    <view class="sure-exchange-desc">
      仅差一步，即可兑换成功，快选择领取方式吧
    </view>
    <view class="select-campus-wrap">
      <view class="wrap-title">
        {{ addressAndCampusContainerTitle }}
      </view>
      <view
        v-if="!isShowAddressCard"
        class="select-campus"
        @tap="handleOperate"
      >
        <!-- 默认按钮 -->
        <view
          class="select-campus-plcaeholder"
          v-if="isShowDefaultSelectText"
          >{{ currentTypeInfo.button }}</view
        >
        <!-- 选择校区 -->
        <view v-if="isShowCampusCard" class="select-campus-content"
          >{{ campusContent.city_title }} ·
          {{ campusContent.campus_title }}</view
        >
        <view class="select-campus-icon"></view>
      </view>
      <!-- 选择收货地址 -->
      <addressCard
        v-if="isShowAddressCard"
        :addressInfo="address"
        @edit="handleEditAddress"
      />
      <view class="apply-mail" :class="toggleTypeBtnClass">
        <view @tap="handleToggleType">
          {{ currentTypeInfo.extraButton }}
        </view>
      </view>
    </view>
    <finishButton :width="690" @click="handleSure" :disabled="isDisabledSure">
      确定
    </finishButton>
    <!-- 选择校区 -->
    <actionSheet
      :is-opened-modal.sync="isShowCampus"
      :height="932"
      :is-show-title="true"
      modal-title="请选择所在地区"
      class="select-campus-modal"
    >
      <selectCampus
        :is-show-campus="isShowCampus"
        :cityList="cityList"
        :selectCampus="campusStack"
        @cancel="handleCancelCampu"
      />
    </actionSheet>
    <!-- toast提示 -->
    <at-toast
      :is-opened="is_opened"
      :text="toastText"
      :on-close="handleCloseToast"
    />

    <!-- 退出弹窗 -->
    <at-modal
      class="custom-confirm"
      :is-opened="isShowModal"
      :on-close="handleModalCancel"
      :on-cancel="handleModalCancel"
    >
      <AtModalContent>
        还差一步即可兑换成功，确定要放弃兑换吗？
      </AtModalContent>
      <AtModalAction>
        <view class="modal-footer" @tap="handleBackOperate">
          <view data-key="back">
            放弃
          </view>
          <view data-key="no-back">
            继续兑换
          </view>
        </view>
      </AtModalAction>
    </at-modal>
  </view>
</template>

<script>
import Taro from "@tarojs/taro";
import customHeader from "@/components/custom-header";
import finishButton from "@/components/finish-button/index";
import selectCampus from "../components/select-campus";
import actionSheet from "@/components/action-sheet/index";
import addressCard from "@/components/address-card/index";
import { getLetterSortCitys, getRegionCampus } from "@/libs/api/base-api";
import { address } from "@/libs/api/mine";
import { getAddress, physicalGoodsExchange } from "@/libs/api/exchange-store";
const MAIL_TYPE = 1; // 邮寄
const OFFLINE_TYPE = 2;
const MAX_STACK_LEN = 3;
const exchangeType = [
  {
    type: OFFLINE_TYPE,
    title: "线下领取",
    button: "选择校区",
    extraButton: "我要申请邮寄"
  },
  {
    type: MAIL_TYPE,
    title: "我要申请邮寄",
    button: "暂无地址，添加收获地址",
    extraButton: "线下领取"
  }
];
/**库存不足报错状态码 */
const Not_Enough_Stock_Code = 4002;
/**栏目下架错误状态码 */
const CATE_OFF_CODE = 4003;
export default {
  components: {
    finishButton,
    selectCampus,
    actionSheet,
    addressCard,
    customHeader
  },
  data() {
    return {
      info: {},
      currentType: OFFLINE_TYPE,
      isShowCampus: false,
      listStack: [],
      campusStack: [],
      cityList: [],
      address: null,
      midAddress: {},
      listIndex: 0,
      isFromMore: false
    };
  },
  computed: {
    currentTypeInfo() {
      return exchangeType.find(i => i.type === this.currentType) || {};
    },
    /**是否为线下领取 */
    isOfflineType() {
      return this.currentType === OFFLINE_TYPE;
    },
    /**校区是否为全填写 */
    isFullCampus() {
      return this.campusStack.length === MAX_STACK_LEN;
    },
    campusContent() {
      const [city, region, campus] = this.campusStack;
      return {
        city_title: city.title,
        campus_title: campus.title
      };
    },
    /**切换领取方式的class */
    toggleTypeBtnClass() {
      return {
        "apply-mail-type": !this.isOfflineType
      };
    },
    isShowDefaultSelectText() {
      return !this.isShowCampusCard && !this.isShowAddressCard;
    },
    isShowCampusCard() {
      return this.isFullCampus && this.isOfflineType;
    },
    isShowAddressCard() {
      return this.address && !this.isOfflineType;
    },
    /**地址校区选择区域的标题 */
    addressAndCampusContainerTitle() {
      return this.isShowAddressCard
        ? "请确认收货地址"
        : this.currentTypeInfo.title;
    },
    /**是否禁止确认按钮 */
    isDisabledSure() {
      return this.isOfflineType ? !this.isFullCampus : !this.address;
    }
  },
  onLoad({ data, ismore }) {
    this.info = data ? JSON.parse(data) : {};
    this.isFromMore = !!~~ismore;
  },
  onShow() {
    this.handleInitGetAddress();
  },
  created() {
    this.handleGetCityList();
  },
  methods: {
    handleCancelCampu(data) {
      this.campusStack = [...data];
      this.isShowCampus = false;
    },
    handleInitGetAddress() {
      if (!this.isOfflineType) {
        this.handleGetAddress();
      }
    },
    /**获取收获地址 */
    async handleGetAddress() {
      const { data } = await address();
      this.address = data;
    },
    /**修改校区时，切换城市等 */
    handleRegetFullStatusList(ind) {
      this.listStack = this.listStack.slice(0, ind + 1);
      this.fullList = this.listStack[ind];
    },
    /**获取城市带字母列表 */
    async handleGetCityList() {
      const { data } = await getLetterSortCitys();
      this.cityList = data;
    },
    /**获取区级校区 */
    async handleGetRegionCampus(city_id) {
      this.$startLoading();
      const [err, { data }] = await this.$captureCatch(
        getRegionCampus({ city_id })
      );
      this.$endLoading();
      if (err) return this.$message(err.message);
      this.listStack.push(data);
    },
    /**编辑收货地址 */
    handleEditAddress() {
      this.handleToAddress(true);
    },
    /**选择校区or添加地址 */
    handleOperate() {
      /**选择校区 */
      if (this.isOfflineType) {
        if (!this.isFullCampus) {
          this.campusStack = [];
          this.listIndex = 0;
        }
        this.isShowCampus = true;
        return;
      }
      /**新增收货地址 */
      this.handleToAddress();
    },
    /**跳转收货地址或编辑地址 */
    handleToAddress(isEdit = false) {
      Taro.navigateTo({
        url: `/pages/address-edit/index?isEdit=${Number(isEdit)}`
      });
    },
    /**切换兑换方式 */
    handleToggleType() {
      this.currentType = this.isOfflineType ? MAIL_TYPE : OFFLINE_TYPE;
      this.campusStack = [];
      this.listIndex = 0;
      if (!this.isOfflineType && !this.address) {
        this.handleGetAddress();
      }
    },
    handleSure() {
      if (this.isOfflineType && !this.isFullCampus) return;
      let campu_id = undefined;
      if (this.isOfflineType) {
        const [campusInfo] = this.campusStack.slice(-1);
        campu_id = campusInfo?.id;
      }
      const query = {
        id: this.info.id,
        is_offline: Number(this.isOfflineType),
        campu_id
      };
      if (this.isLoading) return;
      this.isLoading = true;
      physicalGoodsExchange(query)
        .then(({ data }) => {
          setTimeout(() => {
            this.isLoading = false;
          }, 500);
          data = JSON.stringify(data || {});
          Taro.navigateTo({
            url: `/pages/exchange-store/exchange-result/index?isEntityGoods=${true}&teacher=${data}`
          });
        })
        .catch(({ message, status_code }) => {
          setTimeout(() => {
            this.isLoading = false;
          }, 500);
          if (status_code === CATE_OFF_CODE) {
            /**如果是更多商品跳转过来的 应返回2级 */
            const delta = this.isFromMore ? 3 : 2;
            Taro.navigateBack({
              delta,
              success: () => {
                Taro.eventCenter.trigger("get-error", message);
              }
            });
            return;
          }
          /**库存不足 */
          if (status_code === Not_Enough_Stock_Code) {
            Taro.navigateTo({
              url: `/pages/exchange-store/exchange-result/index?notStock=${true}`
            });
            return;
          }
          this.$message(message);
        });
    },
    handleBackPrevPage() {
      this.isShowModal = true;
    },
    handleBackOperate({ target: { dataset } }) {
      const { key } = dataset;
      if (key === "no-back") {
        this.isShowModal = false;
        return;
      }
      Taro.navigateBack({ delta: 1 });
    }
  }
};
</script>

<style lang="scss">
@import "@/assets/scss/tools.scss";
.sure-exchange {
  background-color: #fafafa;
  height: 100vh;
  &-title {
    background-color: #ffffff;
    padding: 30px 30px 0;
    box-sizing: border-box;
    width: 100%;
    height: 272px;
    @include normal-flex(left);
    margin-bottom: 32px;
    .head-img {
      width: 200px;
      height: 200px;
      vertical-align: top;
      border-radius: 16px;
      margin-right: 32px;
    }
    .head-title {
      flex: 1;
      view:first-child {
        @include base-text(92px, 40px, #000000);
        margin-bottom: 52px;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        line-height: 48px;
      }
      view:last-child {
        @include normal-flex(left);
        text:last-child {
          @include normal-flex(left);
          @include base-text(56px, 32px, #303133, 400);
        }
        text:first-child {
          margin-right: 4px;
          @include base-text(56px, 40px, #ff8000);
        }
      }
    }
  }
  &-desc {
    margin-bottom: 32px;
    padding-left: 30px;
    line-height: 40px;
    @include base-text(40px, 28px, #ff8000, 400);
  }
  .select-campus-wrap {
    padding: 32px 30px 48px;
    background-color: #ffffff;
    min-height: 314px;
    .wrap-title {
      @include base-text(50px, 36px, #303133);
      margin-bottom: 24px;
    }
    .select-campus {
      border-radius: 16px;
      background-color: #fafafa;
      height: 88px;
      padding: 0 32px;
      margin-bottom: 32px;
      @include normal-flex(left);
      &-plcaeholder {
        flex: 1;
        @include base-text(44px, 32px, #c0c4cc, 400);
      }
      &-content {
        flex: 1;
        @include textEllipsis;
        @include base-text(44px, 32px, #303133, 400);
      }
      &-icon {
        width: 44px;
        height: 44px;
        @include setBgi("~@/assets/icon/right.png");
      }
    }

    .apply-mail {
      @include normal-flex(flex-end);
      view {
        padding-right: 34px;
        display: block;
        @include base-text(40px, 28px, #909399, 400);
        @include setBgi("~@/assets/icon/right.png");
        background-position-x: right;
        background-size: 40px 40px;
      }
      &-type view {
        color: #ff8000;
        @include setBgi("~@/assets/icon/address-right.png");
        background-size: 40px 32px;
        background-position-y: 4px;
        padding-right: 26px;
      }
    }
  }
  .finish-button-wrap {
    position: fixed;
    bottom: 16px;
    left: 50%;
    transform: translateX(-50%);
  }
  .select-campus-modal {
    .custom-comtainer-wrap {
      padding: 24px 30px 0;
    }
  }
  .address-card {
    margin-bottom: 32px;
  }
  .custom-header {
    background-color: #ffffff;
  }
}
</style>
